/*
 * JNameChooserFrame.java
 *
 * Created on 27. August 2008, 14:38
 */

package jnamechooser;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import javax.swing.JOptionPane;

/**
 *
 * @author  uli
 */
public class JNameChooserFrame extends javax.swing.JFrame {

    /** Creates new form JNameChooserFrame */
    public JNameChooserFrame() {
        initComponents();
        establishConnection();
    }
    
    private void establishConnection()
    {
        try
        {
            //Setup connection
            connection = DriverManager.getConnection(connectionURL, username, password);
            //setup();
            //Setup prepared statements
            searchMaleStatement = connection.prepareStatement("SELECT Name FROM firstnames WHERE Female = 0");
            searchFemaleStatement = connection.prepareStatement("SELECT Name FROM firstnames WHERE Female = 1");
            countFemaleStatement = connection.prepareStatement("SELECT COUNT(Name) FROM firstnames WHERE Female = 1");
            countMaleStatement = connection.prepareStatement("SELECT COUNT(Name) FROM firstnames WHERE Female = 0");
            searchSurnameStatement = connection.prepareStatement("SELECT Name FROM surnames");
            countSurnameStatement = connection.prepareStatement("SELECT COUNT(Name) FROM surnames");
            insertFirstnameStatement = connection.prepareStatement("INSERT INTO firstnames VALUES(?,?)");
            insertSurnameStatement = connection.prepareStatement("INSERT INTO surnames VALUES(?)");
        }
        catch (SQLException ex)
        {
            JOptionPane.showMessageDialog(this, ex, "SQL Error", JOptionPane.ERROR_MESSAGE);
            
        }
    }
    
    private void setup()
    {
        try
        {
            Statement stmt = connection.createStatement();
            //Create table firstnames
            stmt.executeUpdate("CREATE TABLE firstnames (Name VARCHAR(200), Female SMALLINT)");
            //Create table surnames
            stmt.executeUpdate("CREATE TABLE surnames (Name VARCHAR(200))");
        }
        catch (SQLException ex)
        {
            JOptionPane.showMessageDialog(this, ex, "SQL Error", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        nameLabel = new javax.swing.JLabel();
        nameValueLabel = new javax.swing.JLabel();
        femaleCheckbox = new javax.swing.JCheckBox();
        addButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JNameChooser");

        okButton.setText("OK");
        okButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                okButtonMouseClicked(evt);
            }
        });

        nameLabel.setText("Name:");

        nameValueLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        nameValueLabel.setText("No name yet!");

        femaleCheckbox.setText("Female");

        addButton.setText("Add");
        addButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(femaleCheckbox)
                        .addGap(18, 18, 18)
                        .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE))
                    .addComponent(okButton, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(nameLabel)
                        .addGap(18, 18, 18)
                        .addComponent(nameValueLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(femaleCheckbox)
                    .addComponent(addButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nameLabel)
                    .addComponent(nameValueLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void addButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addButtonMouseClicked
    new AddNamesDialog(this,
                       true,
                        new PreparedStatement[]{insertSurnameStatement, insertFirstnameStatement})
                                .setVisible(true);
}//GEN-LAST:event_addButtonMouseClicked

private void okButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_okButtonMouseClicked
    try
        {
            StringBuilder nameBuilder = new StringBuilder();
            ResultSet firstNames;
            ResultSet firstNameCount;
            if (femaleCheckbox.isSelected())
                {
                    firstNames = searchFemaleStatement.executeQuery();
                    firstNameCount = countFemaleStatement.executeQuery();
                }
            else
                {
                    firstNames = searchMaleStatement.executeQuery();
                    firstNameCount = countMaleStatement.executeQuery();
                }
            //Determinate firstname
            firstNames.next();
            firstNameCount.next();
            int names = firstNameCount.getInt(1); //Count of rows();
            int rand = random.nextInt(names);
            for(int i = 0;i < rand;i++) {firstNames.next();}
            nameBuilder.append(firstNames.getString(1));
            nameBuilder.append(' ');
            firstNames.close();
            firstNameCount.close();
            //Determinate surname
            //Determinate the row count of surnames
            ResultSet surnameCount = countSurnameStatement.executeQuery();
            surnameCount.next();
            names = surnameCount.getInt(1);
            rand = random.nextInt(names);
            surnameCount.close();
            //Determinate the surname
            ResultSet surnames = searchSurnameStatement.executeQuery();
            surnames.next();
            for(int i = 0;i < rand;i++) {surnames.next();}
            nameBuilder.append(surnames.getString(1));
            surnames.close();
            
            nameValueLabel.setText(nameBuilder.toString());            
        }
    catch (SQLException ex) {JOptionPane.showMessageDialog(this, ex, "SQL Error", JOptionPane.ERROR_MESSAGE);ex.printStackTrace();}//GEN-LAST:event_okButtonMouseClicked
}                                     

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JNameChooserFrame().setVisible(true);
            }
        });
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        connection.close();
    }


    
    //Database variables
    private Connection connection;
    private PreparedStatement searchMaleStatement;
    private PreparedStatement searchFemaleStatement;
    private PreparedStatement searchSurnameStatement;
    private PreparedStatement countFemaleStatement;
    private PreparedStatement countMaleStatement;
    private PreparedStatement countSurnameStatement;
    PreparedStatement insertFirstnameStatement;
    PreparedStatement insertSurnameStatement;
    Random random = new Random();
    private String connectionURL = "jdbc:derby://localhost:1527/Names";
    private String username = "Names";
    private String password = "Names";

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JCheckBox femaleCheckbox;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JLabel nameValueLabel;
    private javax.swing.JButton okButton;
    // End of variables declaration//GEN-END:variables

}
